package com.qiche.aspect;

import com.qiche.config.YmlConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.qiche.enums.ResultEnum;
import com.qiche.model.StoreMember;
import com.qiche.service.StoreMemberService;

/**
 * @author LB
 *
 * @date 2018年6月2日
 */
@Aspect
@Component
public class AccessTokenAspect {

	private ThreadLocal<Long> elaspedTime = new ThreadLocal<Long>();

	private final static Logger log = LoggerFactory.getLogger(AccessTokenAspect.class);

	@Autowired
	private YmlConfig ymlConfig;

	@Autowired
	private StoreMemberService storeMemberService;

	@Pointcut(value = "execution(public * com.qiche.controller.wx..*.*(..))")
	public void accessToken() {
	};

	@Around(value = "accessToken()")
	public Object doAround(ProceedingJoinPoint  joinPoint) throws Throwable {
		Object object = Result.createByErrorMessage("参数不能为空请传入accseeToekn");
		// 访问目标方法的参数：
		Object[] args = joinPoint.getArgs();
		log.info("请求参数:{}",args[0]);
		if (args != null && args.length > 0 && args[0].getClass() == String.class) {
			StoreMember storeMember;
			if (args[2]==null) {
				storeMember = storeMemberService.selectByOpenidMerchantid(args[1].toString(),
						Long.valueOf(args[3].toString()));
			} else {
				storeMember = storeMemberService.selectByOpenidUnionidMerchantid(args[1].toString(), args[2].toString(),
						Long.valueOf(args[3].toString()));
			}
			if(storeMember==null){
			storeMember = new StoreMember();
			storeMember.setMerchantId(Long.valueOf(args[3].toString()) );
			storeMember.setOpenid(args[1].toString());
			if(args[2]!=null){
			storeMember.setUnionid(args[2].toString());
			}
			storeMemberService.save(storeMember);
			}
			StringBuilder sb = new StringBuilder();
			if (StringUtils.isNotEmpty(storeMember.getUnionid())) {
				sb.append(storeMember.getUnionid());
			}
			sb.append(storeMember.getOpenid());
			sb.append(ymlConfig.getAccessTokenKey());
			// 进行MD5加密
			String result = DigestUtils.md5Hex(sb.toString()).toUpperCase();
			if (args[0].equals(result)) {
				args[4] = storeMember;
				object = joinPoint.proceed(args);// 执行该方法
			} else {
				object = Result.createByResultEnum(ResultEnum.ACCESSTOKEN_ERROR);
			}
		}
		// 用改变后的参数执行目标方法
		return object;

	}

}
